#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json

import requests

hot_rank_url = "https://r.inews.qq.com/gw/event/pc_hot_ranking_list?ids_hash=&offset=0&page_size=50&appver=15.5_qqnews_7.1.60"

article_type = {
    "0": "文章",
    "4": "视频",
    "116": "事件",
    "118": "短视频",
    "233": "话题"
}


def api_response():
    headers = {
        'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko)"
                      " Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.58"
    }
    res = requests.get(hot_rank_url, headers=headers)
    return json.loads(res.text)


def parse_response_data(res_data):
    """
    解析响应内容
    :param res_data:
    :return:
    """
    all_news = []
    for index, data in enumerate(res_data['idlist'][0]["newslist"]):
        if data.get('url'):
            # print(index, data)
            all_news.append({
                "id": data['id'],
                "title": data["title"],
                "abstract": data.get('abstract'),
                "hot_info": {
                    "score": data["hotEvent"]["hotScore"],
                    "is_top": data["hotEvent"].get("is_top"),
                    "title": data['hotEvent']['title'],
                    "ranking": data['hotEvent']['ranking']
                },
                "article_type_code": data['articletype'],
                "article_type": article_type.get(data['articletype'], "其他"),
                "read_count": parse_view_count_handler(data).get('readCount'),
                "timestamp": parse_datetime_handler(data),
                "source": data.get("source"),
                "address": data.get('userAddress'),
                "url": data["url"]
            })
    return all_news


def parse_view_count_handler(news_info: dict) -> dict:
    """
    解析新闻阅读量处理器
    :param news_info: 包含新闻信息的字典，包括文章类型、视频频道等
    :return:
    """
    news_type = news_info.get("articletype")
    if str(news_type) == "4":
        view_value = news_info.get("video_channel", {}).get("video", {}).get("playcount", 0)
    else:
        view_value = news_info.get('readCount', 0)
    return {
        "readCount": view_value
    }


def parse_datetime_handler(news_info: dict) -> int:
    """
    解析新闻信息中的日期时间戳，如果存在且大于0,则返回该时间戳，否则返回0
    :param news_info: 包含新闻信息的字典
    :return:
    """
    timestamp = news_info.get("timestamp")
    if timestamp and timestamp > 0:
        return timestamp
    return 0


if __name__ == '__main__':
    print(parse_response_data(api_response()))
